//Folder.java
package composite.safe;

import java.util.*;

/**
 * @author:youtubezou
 * @version:2012-7-17
 */
public class Folder extends FolderItem {
	LinkedList<FolderItem> list = new LinkedList<FolderItem>();

	public Folder(String name, Folder parent) {
		super(name, parent, false);
	}

	public LinkedList<FolderItem> getItems(){
		return list;
	}
	
	public File getFile(String name){
		return (File)get(name, true);
	}
	
	public Folder getFolder(String name){
		return (Folder)get(name, false);
	}
	
	public boolean md(String name){
		return add(name, false);
	}
	
	public boolean edit(String name){
		return add(name, true);
	}

	public boolean rmdir(String name){
		return remove(name, false);
	}
	
	public boolean rmfile(String name){
		return remove(name, true);
	}
	
	public String  toString(){
		StringBuffer str = new StringBuffer();
		
		/*deep travel*/
		if(getParent() != null){
			str.append(getParent().getName()).append("/");
		}
		
		str.append(getName()).append("\t<Dir>").append("\n");
		for (FolderItem e : list){
			str.append("\t").append(e).append("\n");
		}
		
		return str.toString();
	}
	
	private FolderItem get(String name, boolean isFile){
		FolderItem item = null;
		if(isFile){
			item = new File(name, null);
		} else {
			item = new Folder(name, null);
		}
		
		int index = 0;
		if((index = list.indexOf(item)) != -1){
			return list.get(index);
		}
		
		return null;
	}
	
	private boolean add(String name, boolean isFile) {
		FolderItem item;
		
		if (!isFile)
			item = new Folder(name, this);
		else 
			item = new File(name, this);
		
		if (!isExist(item)) {
			return list.add(item);
		}

		return false;
	}
	
	private boolean remove(String name, boolean isFile){
		FolderItem item;
		
		if (!isFile)
			item = new Folder(name, null);
		else 
			item = new File(name, null);
		
		if(!isExist(item))
			return false;
		return list.remove(item);
	}

	private boolean isExist(FolderItem item) {
		for (FolderItem e : list)
			if (e.equals(item))
				return true;
		return false;
	}

	
}
